const QR = require('../../../utils/wxqcode.js');
const util = require('../../../utils/util.js');
const fsm = wx.getFileSystemManager();
const FILE_BASE_NAME = 'tmp_base64src';
const format="test.png";
const format2 = "qcode.png";
const app = getApp();
var limit = 15;// 每页显示的条数
// pages/canvas/canvas.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hidden: true,
    qrcode: '',
    flag:true,
    currentPage: 1,
    keyword:''
  },

  /**
     * 生命周期函数--监听页面加载
     */
  // 上拉加载更多
  loadMore: function (e) {
    var that = this;
    if (!that.data.nomore) {
      that.setData({
        currentPage: that.data.currentPage + 1,
      })
      util.loading();
      that.getDataofres(that.data.userInfo);
    }
  },
  /**
* 滑动事件
* */
  scroll: function (e) {
    var that = this;
    that.setData({
      scrollTop: e.detail.scrollTop
    })
  },
  onShow: function (e) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight - 20
        });
      }
    });
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,
          dataList: []
        })
        if (res.data.user_type_id == 10006) {
          app.editTabBar2();
          
        } else {
          app.editTabBar();
          
        }
        that.getDataofres(res.data);
        //that.getApartment(res.data);
        //that.getDataofRoom(res.data);
      }, fail: function () {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    });

  },
  getDataofres: function (data) {
    var that = this
    util.getReq("/app/home/roomList", {
      source: data.source,
      uid: data.user_id,
      'startPage': that.data.currentPage,
      "pageSize": limit,
      "keyword":that.data.keyword
    }, function (datas) {
      var dataLists = that.data.dataList;
      util.closeloading();
      wx.stopPullDownRefresh();
      if (datas.code == 0) {
        if (datas.data.data) {
          var len = datas.data.data.length;
          var d = datas.data.data;
          for (var i = 0; i < len; i++) {
            var img = d[i].img_url == null ? d[i].mimg_url : d[i].img_url;
            var addr = d[i].area_name + "-" + d[i].village_name + "-" + d[i].apartment_name + "-" +d[i].room_code;
            if (addr.length > 25) {
              addr = addr.substring(0, 25) + "...";
            }
            var detali = d[i].room_num + '室' + d[i].office_num + '厅' + d[i].toilet_num + '卫-' + d[i].build_area + '㎡';
            var room_show = d[i].room_show == 1 ? '在租' : '已租';
            dataLists.push({
              img: img,
              addr: addr,
              detali: detali,
              room_show: room_show,
              room_id: d[i].room_id,
              month_rent: d[i].month_rent
            });
          }
        }

        that.setData({
          dataList: dataLists
        })

        if (datas.data.pageCount <= that.data.currentPage) {
          that.setData({
            nomore: true
          })

        }
      } else {
        wx.showToast({
          title: datas.desc,
        })
      }
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
   
  
  },
  
  /**
   * 点击生成画布
   */
  execPic:function(e){
    var that=this;
    wx.showLoading({
      title: '加载中请稍后',
      mask: true,
    })

    util.getReq('/app/home/homeDetail', { room_id: e.currentTarget.dataset.id }, function (data) {

      if (data.code == 0) {
        let houseDetail = data.params.houseDetail;
        let imgs = data.params.imgs[0].img_url;
        //设置参数
        let area_name = houseDetail[0].area_name;
        let village_name = houseDetail[0].village_name;
        let address = area_name + '-' + village_name;
        if (address.length > 10) {
          address = address.substring(0, 10) + "...";
        }
        let shi = houseDetail[0].room_num + '室';
        let ting = houseDetail[0].office_num + '厅';
        let wei = houseDetail[0].toilet_num + '卫';
        let build_area = houseDetail[0].build_area + '㎡';
        let roomshow = '已租';
        if (houseDetail[0].room_show == 1) {
          roomshow = '在租';
        }
        let roomconfig = shi + ting + wei + "—" + build_area + "—" + roomshow;
        let yf = '押' + houseDetail[0].deposit_num + '付' + houseDetail[0].rent_num;
        let month_rent = houseDetail[0].month_rent; //租金
        let month_earnest = houseDetail[0].month_earnest;
        let month_depost = houseDetail[0].month_depost;
       
        that.setData({
          address: address,
          imgs: imgs,
          roomconfig: roomconfig,
          yf: yf,
          month_rent: month_rent,
          month_earnest: month_earnest,
          month_depost: month_depost
        })
        //that.startDard(e.currentTarget.dataset.id);
        const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
        const buffer = wx.base64ToArrayBuffer(imgs);
        fsm.writeFile({
          filePath,
          data: buffer,
          encoding: 'binary',
          success(res) {
            console.log(111);
            wx.getImageInfo({
              src: filePath,
              success(re) {
                console.log(re);
               that.setData({
                 imgs:re.path,
               });
                let qrcodeSize = that.getQRCodeSize()
                that.createQRCode(util.shareUtil + "&room_id=" + e.currentTarget.dataset.id, qrcodeSize);
                const filePath2 = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format2}`;
                const buffer = wx.base64ToArrayBuffer(that.data.qrcode);
                fsm.writeFile({
                  filePath: filePath2,
                  data: buffer,
                  encoding: 'binary',
                  success(res) {
                    wx.getImageInfo({
                      src: filePath2,
                      success(re) {
                        that.setData({
                          qrcode: re.path,
                        });
                        that.startDard(e.currentTarget.dataset.id);
                      }, fail(res) {
                        console.log(res);
                        wx.showToast({
                          title: '图片保存失败',
                          icon: 'none',
                        })
                      }
                      })
                      }, fail(res) {
                        wx.showToast({
                          title: '图片保存失败',
                          icon: 'none',
                        })
                      }
                    });    
              },
              fail(re) {
                wx.showToast({
                  title: '图片保存失败',
                  icon: 'none',
                })
              }
            })
          },
          fail(res) {
            console.log(res);
            wx.showToast({
              title: '图片保存失败',
              icon: 'none',
            })
          },
        });
      } else {
        wx.showModal({
          title: '错误',
          content: data.desc,
          mode: true,
          showCancel: false,
          confirmColor: '#007aff',
        })
      }
    })
  },

 /**
  * 开始绘画
  */
 startDard:function(id){
   wx.hideLoading();
   wx.showLoading({
     title: '图片生成中请稍后。。。',
     mask: true,
   })
   var that = this;
   
   const ctx = wx.createCanvasContext('shareImg')
   //主要就是计算好各个图文的位置
   //图片
   let base64Url= that.data.imgs
   //base64Url = base64Url.replace(/\ +/g, ""); //去掉空格方法
   //base64Url = base64Url.replace(/[\r\n]/g, "");
   ctx.setFillStyle("#fff");//设置背景颜色
   ctx.fillRect(0, 0, 300, 350);
   ctx.drawImage(base64Url, 0, 0, 300, 200)//x y w h
   //二维码
   let qrcodeUrl = that.data.qrcode;
   //qrcodeUrl = qrcodeUrl.replace(/\ +/g, ""); //去掉空格方法
   //qrcodeUrl = qrcodeUrl.replace(/[\r\n]/g, "");
   //var array = wx.base64ToArrayBuffer(qrcodeUrl)
   //var base64 = wx.arrayBufferToBase64(array)
   ctx.drawImage(qrcodeUrl, 200, 200, 100, 80)//x y w h
   //长按识别二维码
   let changan = { x: 210, y: 290, color: '#333', size: 10, align: 'left', baseline: 'middle', text: "长按识别二维码", bold: false }; that.drawText(ctx, changan);

   let address = { x: 20, y: 220, color: '#333', size: 18, align: 'left', baseline: 'middle', text: that.data.address, bold: true };        that.drawText(ctx, address);
 
   let roomconfig = { x: 20, y: 240, color: '#333', size: 12, align: 'left', baseline: 'top', text: that.data.roomconfig, bold: false }; that.drawText(ctx, roomconfig);
 
   let fkfs = { x: 20, y: 270, color: '#333', size: 14, align: 'left', baseline: 'top', text: "付款方式", bold: true }; 
   that.drawText(ctx, fkfs);
   let yf = { x: 100, y: 272, color: '#333', size: 10, align: 'center', baseline: 'top', text: that.data.yf, bold: false };       that.drawText(ctx, yf);

   let zujin = { x: 20, y: 300, color: '#333', size: 14, align: 'left', baseline: 'top', text: "租金", bold: false };
   that.drawText(ctx, zujin);
  
   let month_rent = { x: 60, y: 300, color: '#3F87F6', size: 14, align: 'left', baseline: 'top', text: that.data.month_rent, bold: false };
   that.drawText(ctx, month_rent);
  
   let yajin = { x: 100, y: 300, color: '#333', size: 14, align: 'left', baseline: 'top', text: "押金", bold: false };
   that.drawText(ctx, yajin);
  
   let month_depost = { x: 140, y: 300, color: '#3F87F6', size: 14, align: 'left', baseline: 'top', text: that.data.month_depost, bold: false };
   that.drawText(ctx, month_depost);
  
   let dingjin = { x: 180, y: 300, color: '#333', size: 14, align: 'left', baseline: 'top', text: "定金", bold: false };
   that.drawText(ctx, dingjin);

   let month_earnest = { x: 220, y: 300, color: '#3F87F6', size: 14, align: 'left', baseline: 'top', text: that.data.month_earnest, bold: false };
   that.drawText(ctx, month_earnest);
  
   ctx.draw();
   ctx.stroke();

  
   setTimeout(function () { that.share(); }, 3000);
 },
  /**
   * 生成分享图
  */
  share: function () {
    var that = this
    wx.showLoading({
      title: '努力生成中...'
    })
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 300,
      height: 350,
      destWidth: 300,
      destHeight: 350,
      canvasId: 'shareImg',
      quality:'1',
      success: function (res) {
        console.log(res.tempFilePath);
        that.setData({
          prurl: res.tempFilePath,
          hidden: false,
          flag: false
        })
        wx.hideLoading()
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },

  /**
   * 保存到相册
  */
  saveImg: function () {
    var that = this
    //生产环境时 记得这里要加入获取相册授权的代码
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showToast({
          title: '保存成功,请进入相册进行查看',
          icon:'none'
        })
        setTimeout(function () { }, 3000);
      }
    })

  },
  //二维码
  getQRCodeSize: function () {
    var size = 0;
    try {
      var res = wx.getSystemInfoSync();
      var scale = res.windowWidth / 750; //不同屏幕下QRcode的适配比例；设计稿是750宽
      var width = 300 * scale;
      size = width;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
      size = 150;
    }
    return size;
  },
  createQRCode: function (text, size) {
    //调用插件中的draw方法，绘制二维码图片
    let that = this
    try {
      // console.log('QRcode: ', text, size)
      let _img = QR.createQrCodeImg(text, {
        size: parseInt(size),
        typeNumber:5
      })
      that.setData({
        'qrcode': _img
      })
    } catch (e) {
      console.log(e)
    }
  },
  drawText: function (ctx, obj) {
    console.log('渲染文字')
   
    ctx.save(); 
    ctx.setFillStyle(obj.color);
    ctx.setFontSize(obj.size); 
    ctx.setTextAlign(obj.align); 
    ctx.setTextBaseline(obj.baseline);
   
    if (obj.bold) {
      console.log('字体加粗')           
      ctx.fillText(obj.text, obj.x, obj.y - 0.5);
       ctx.fillText(obj.text, obj.x - 0.5, obj.y);
    }
     ctx.fillText(obj.text, obj.x, obj.y);
     if (obj.bold) {
       ctx.fillText(obj.text, obj.x, obj.y + 0.2);
       ctx.fillText(obj.text, obj.x + 0.2, obj.y);
    } 
    ctx.restore();
  },
  /**
   * 文本换行
   */
  textWrap: function (obj, ctx) {
    console.log('文本换行')    
    let tr = this.getTextLine(obj, ctx);
     for (let i = 0; i < tr.length; i++) {
      if (i < obj.line) {
        let txt = {
          x: obj.x, y: obj.y + (i * obj.height), color: obj.color, size: obj.size, align: obj.align, baseline: obj.baseline, text: tr[i], bold: obj.bold
        }; if (i == obj.line - 1) {
          txt.text = txt.text.substring(0, txt.text.length - 3) + '......';
        } 
        ctx.drawText(txt);
      }
    }
  },
  getTextLine: function (obj, ctx) {
   ctx.setFontSize(obj.size); 
    let arrText = obj.text.split('');
     let line = ''; 
     let arrTr = []; 
     for (let i = 0; i < arrText.length; i++) {
      var testLine = line + arrText[i]; 
      var metrics = ctx.measureText(testLine); 
      var width = metrics.width;
       if (width > obj.width && i > 0) {
        arrTr.push(line);
        line = arrText[i];
      } else {
        line = testLine;
      } if (i == arrText.length - 1) {
        arrTr.push(line);
      }
    } return arrTr;
  },
  /**
   * 关闭
   */
  closeMask: function () {
    this.setData({ flag: true })
  },
  /**
   * 搜索
   */
  wxSearchInput:function(e){
    this.setData({
      keyword:e.detail.value
    })
  },
  bindSearch:function(e){
    var that=this;
    that.setData({
      nomore: false,
      currentPage: 1,
      dataList: []
    })
    that.getDataofres(that.data.userInfo);
  }
})